namespace Todos.Application.TodoItems.Commands;

[AuthConfig(typeof(TodoItem), ResourceAccessType.RoleLimit, "Update")]
public class UpdateTodoItemCommand : IRequest<ApiResult>, ICommand
{
    public long ListId { get; set; }

    public TodoItemInDto[] Dtos { get; set; } = [];
}

public class UpdateTodoItemCommandHandler(IRepository<TodoList> repository) : IRequestHandler<UpdateTodoItemCommand, ApiResult>
{    public async Task<ApiResult> Handle(UpdateTodoItemCommand request, CancellationToken cancellationToken)
    {
        var spec = new TodoListByIdSpec(request.ListId).And(new TodoListIncludeItemsSpec());
        var list = await repository.GetAsync(spec, cancellationToken);
        if (list == null)
        {
            return new ApiResult(ApiResultType.Error, "待办列表不存在");
        }

        foreach (var dto in request.Dtos)
        {
            list.UpdateItem(dto.Id, dto.Title, dto.Description, dto.Status, dto.IsLocked);
        }

        await repository.UpdateAsync(list, cancellationToken);
        return new ApiResult(ApiResultType.Success, $"{request.Dtos.Length}个待办项更新成功");
    }
}

public class UpdateTodoItemCommandValidator : AbstractValidator<UpdateTodoItemCommand>
{
    public UpdateTodoItemCommandValidator()
    {
        RuleFor(m => m.ListId).NotEmpty().WithMessage("待办列表Id不能为空");
        RuleFor(m => m.Dtos).NotEmpty().WithMessage("待办项不能为空");
        RuleForEach(m => m.Dtos).ChildRules(dto =>
        {
            dto.RuleFor(m => m.Id).NotEmpty().WithMessage("待办项Id不能为空");
            dto.RuleFor(m => m.Title).NotEmpty().WithMessage("待办项标题不能为空")
                .MaximumLength(255).WithMessage("待办项标题长度不能超过255个字符");
            dto.RuleFor(m => m.Description).MaximumLength(1000).WithMessage("待办项描述长度不能超过1000个字符");
        });
    }
}
